import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:scrollview_observer/scrollview_observer.dart';
import 'package:sports_new/controller/home/comment_view_logic.dart';
import 'package:sports_new/controller/home/news_detail_logic.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/app_config.dart';
import 'package:sports_new/utils/local_read_history.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/expert/items/plan_item.dart';
import 'package:sports_new/view/home/comments/comment_input_widget.dart';
import 'package:sports_new/view/home/comments/news_comments_view.dart';
import 'package:sports_new/view/home/comments/news_share_append.dart';
import 'package:sports_new/view/home/news_cell.dart';
import 'package:sports_new/widgets/card.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/share/share_sheet.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:sports_new/view/home/news_detail_view.dart';
import 'package:sports_new/view/home/post_cell.dart';
import '../../widgets/base/qkd_text.dart';

class NewsDetailPage extends StatefulWidget {
  const NewsDetailPage({super.key});

  @override
  State<NewsDetailPage> createState() => _NewsDetailPageState();
}

class _NewsDetailPageState extends State<NewsDetailPage> {
  int id = "${Get.arguments}".toInt() ?? 0;
  late final NewsDetailLogic logic;
  late final CommentViewLogic commentLogic;

  late int? classId = int.tryParse(Get.parameters['classId'] ?? "");
  EasyRefreshController refreshC =
      EasyRefreshController(controlFinishLoad: true);

  // late final commentsController = NewsCommentsController(id ?? 0);
  final scrollC = ApmScrollController();
  bool showTop = false;

  late ListObserverController observerController;

  @override
  void initState() {
    super.initState();
    // commentsController.fetchCommentds();
    // AppNewsFloat2Widget.delNews(id);
    Utils.onEvent('zx_ck');
    logic = Get.put(NewsDetailLogic(), tag: '${Get.arguments}');
    commentLogic = Get.put(CommentViewLogic(), tag: '${Get.arguments}');
    LocalReadHistory.readNews("${logic.newsId}");
    observerController = ListObserverController(controller: scrollC);
    scrollC.addListener(() {
      if (scrollC.offset > 60 && showTop == false) {
        showTop = true;
        update();
      } else if (scrollC.offset < 60 && showTop == true) {
        showTop = false;
        update();
      }
    });
  }

  @override
  void dispose() {
    scrollC.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    bool loading = logic.data.toString().isEmpty;

    if (loading) {
      return const CircularProgressIndicator();
    } else {
      return GetBuilder<NewsDetailLogic>(
        tag: '$id',
        builder: (_) => Scaffold(
          resizeToAvoidBottomInset: false,
          backgroundColor: Colours.greyF2F3F7,
          appBar: Styles.appBar(
            titleSpacing: 0,
            // toolbarHeight: kToolbarHeight,
            // title: Image.asset(Utils.getImgPath("qxb_title.png")),
            title: showTop
              ? Styles.userAppbarTitle(
                logo: logic.data?.logo,
                name: logic.data?.publisherName,
                focus: logic.data?.focus,
                userId: logic.data?.publisherId,
                onTap: (value) => logic.getNews()
            ) : const QkdText('内容详情'),
            actions: [
              GestureDetector(
                onTap: () async {
                  Utils.onEvent("zxxq", params: {"zxxq": 1});
                  final news = logic.data;
                  final classId = logic.classId;
                  if (news == null) {
                    return;
                  }
                  Get.bottomSheet(
                    ShareSheet(append: NewsShareAppend(news: news, classId: classId)),
                    settings: RouteSettings(
                      arguments: ShareEntity(
                        url: 'tg/articles/${news.id}'
                      )
                    )
                  );
                },
                child: SizedBox(
                  height: Get.height,
                  child: Image.asset(
                    Utils.getImgPath("news_detail_more.png"),
                    width: 24,
                    height: 24,
                  ).marginOnly(right: 16),
                ),
              )
            ]
          ),
          body: LoadingWidget<bool>(
            isLoading: logic.data == null,
            reconnect: logic.getRefresh,
            data: logic.data?.id == null,
            child: () => Column(
              children: [
                Expanded(
                  child: ListViewObserver(
                    controller: observerController,
                    child: ListView(controller: scrollC, children: [
                      Column(
                        children: [
                          logic.data?.type == 2 ?
                          PostCell(logic.data!, type: 1,) :
                          NewsDetailView(data: logic.data),
                          ...logic.plan?.map(
                            (e) => Block(
                              cardStyle: const CardStyle(
                                margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
                                padding: EdgeInsets.symmetric(horizontal: 12)
                              ),
                              child: PlanItem(
                                entity: e,
                                eventType: "zx_ckfa",
                              )
                            )
                          ).toList() ?? [],
                          if (logic.data?.list?.hasValue == true && AppConfig.config.showRelative)
                            recommendNews(),
                        ],
                      ),
                      Container(
                        color: Colours.scaffoldBg,
                        padding: const EdgeInsets.only(top: 8),
                        constraints: BoxConstraints(
                          minHeight: Get.height -
                            MediaQuery.of(context).padding.top -
                            MediaQuery.of(context).padding.bottom - 54
                        ),
                        child: GetBuilder<CommentViewLogic>(
                          tag: '$id',
                          builder: (_) {
                            return NewsCommentsView(id,
                              paddingTop: MediaQuery.of(context)
                                .padding.top
                            );
                          },
                        )
                      )
                    ]),
                  ),
                ),
                SafeArea(
                  top: false,
                  child: GetBuilder<CommentViewLogic>(
                    tag: '$id',
                    builder: (_) {
                      return Container(
                        color: Colours.white,
                        child: CommentInputWidget(
                          afterShare: () => update(),
                          canInput: (bool isbtn) {
                            if (isbtn) {
                              if (scrollC.offset == 0) {
                                Future.delayed(
                                  const Duration(milliseconds: 100)
                                ).then((value) {
                                  observerController.animateTo(
                                    index: 1,
                                    duration: const Duration(milliseconds: 200),
                                    curve: Curves.linear
                                  );
                                });
                                return false;
                              } else {
                                scrollC.animateTo(0,
                                  duration: const Duration(
                                    milliseconds: 200
                                  ),
                                  curve: Curves.linear);
                                return false;
                              }
                            }
                            return true;
                          },
                          news: logic.data,
                          newsId: id,
                          cid: classId,
                          textId: "$id"
                        ),
                      );
                    },
                  )
                )
              ],
            ),
          ),
        ),
      ).tap(() {
        FocusScope.of(context).unfocus();
      });
    }
  }

  Widget recommendNews() {
    return Container(
      color: Colours.scaffoldBg,
      // padding: const EdgeInsets.only(top: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          QkdText(
            "相关资讯",
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ).marginOnly(top: 12, left: 16),
          ...List.generate(
              logic.data!.list!.length,
              (index) => NewsItemCell(
                    logic.data!.list![index],
                    classId: classId,
                    inHome: false,
                    imgStyle: logic.data!.list![index].imgStyle,
                    bottomDivider: index != logic.data!.list!.length - 1,
                    afterRoute: () => update(),
                onTap: () => Utils.onEvent('zxxq',params: {'zxxq':4}),
                  )),
          // ...recommendList.map((e) => NewsListCell(e,classId: classId,inHome: false,afterRoute: () => update(),))
        ],
      ),
    );
  }
}
